const express = require('express')
const { Types } = require('mongoose')
const router = express.Router()
const {branchModel,userModel} = require('../model/models')
// 展示
router.get('/branchs', async(req,res)=>{
    let data = await branchModel.find().populate('responsible').populate('b_id')
    res.send({
        code:200,
        data
    })
})
// 添加部门
router.post('/createbranch',async(req,res)=>{
    let body = req.body
    if(!body.b_id){
        delete body.b_id
    }
    let branch = await branchModel.create(body)
    res.send({
        code:200,
        msg:'添加成功'
    })
})
// 删除部门
router.delete('/delbranch/:id',async(req,res)=>{
    let id = req.params.id
    await branchModel.deleteOne({_id:id})
    res.send({
        code:200,
        msg:'删除成功'
    })
})
// 修改部门
router.patch('/editbranch/:id',async(req,res)=>{
    let id = req.params.id
    let body = req.body
    // console.log(body);
    let branch = await branchModel.findOne({_id:id})
    await branchModel.updateOne({_id:id},{$set:body})
    if(branch.responsible != body.responsible){ 
        await userModel.updateOne({_id:body.responsible},{$set:{b_id:null}})
    }
    res.send({
        code:200,
        msg:'修改成功'
    })
})

module.exports = router